/*
 * IBM Corporation.
 * Copyright (c) 2014 All Rights Reserved.
 */

package com.ibm.iisp.common.dao.eclipselink;

import java.util.Collection;
import java.util.Map;

import org.eclipse.persistence.config.SessionCustomizer;
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectToFieldMapping;
import org.eclipse.persistence.sessions.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ibm.iisp.common.util.StringUtilsExt;

/**
 * 类作用：用于改变数据库字段命名规，把大小写连接改成"_"连接
 *
 * @author Johnny@cn.ibm.com 使用说明： &lt;property
 *         name="eclipselink.session.customizer" value=
 *         "com.ibm.iisp.common.dao.eclipselink.ImprovedNameMappingCustomizer"
 *         /&gt;
 */
public class ImprovedNameMappingCustomizer implements SessionCustomizer {
	Logger log = LoggerFactory.getLogger(getClass());

	@Override
	public void customize(Session session) throws Exception {
		@SuppressWarnings("rawtypes")
		Map<Class, ClassDescriptor> descs = session.getDescriptors();
		Collection<ClassDescriptor> descriptors = descs.values();
		for (ClassDescriptor desc : descriptors) {
			updateMappings(desc);
		}
	}

	private void updateMappings(ClassDescriptor desc) {
		String tableName = desc.getTableName();
		for (DatabaseMapping mapping : desc.getMappings()) {
			if (mapping.isDirectToFieldMapping()) {
				String attrName = mapping.getAttributeName();
				if (attrName.toUpperCase().equals(mapping.getField().getName())) {
					String oldName = mapping.getField().getName();
					DirectToFieldMapping directMapping = (DirectToFieldMapping) mapping;
					String newName = StringUtilsExt.toUnderscopeSeperated(attrName);
					if (!newName.equals(oldName)) {
						log.debug("{}.{} -> {}", tableName, oldName, newName);
						directMapping.getField().setName(newName);
					}
				}
			}
		}
	}

}